package leetcode;

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int n = nums.length;
        int maxn = Integer.MIN_VALUE;
        int right = -1;

        int minn = Integer.MAX_VALUE;
        int left = -1;

        for (int i = 0; i < n; i++) {
            if (maxn > nums[i]) {
                right = i;
            } else {
                maxn = nums[i];
            }

            if (minn < nums[n - i - 1]) {
                left = n - i - 1;
            } else {
                minn = nums[n - i - 1];
            }
        }

        return right == -1 ? 0 : right - left + 1;
    }
}

public class Test4 {
    public static void main(String[] args) {
        int[] nums = {2,6,4,8,10,9,15};
        Solution solution = new Solution();
        solution.findUnsortedSubarray(nums);
    }
}
